package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiDuMapProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.GeoDistinctUtil;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author moningxi
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private AddressBookMapper addressBookMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private WeChatPayUtil weChatPayUtil;
    @Resource
    private BaiDuMapProperties baiDuMapProperties;
    @Resource
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        Long userId = BaseContext.getCurrentId();
        // 处理异常 地址和购车为空
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        checkDistance(addressBook);
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> carts = shoppingCartMapper.queryByUserAndDishInfo(shoppingCart);
        if (carts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 插入订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(UUID.randomUUID().toString().replaceAll("-", ""));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orderMapper.insert(orders);

        // 添加订单明细
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : carts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);

        // 清空购物车
        shoppingCartMapper.clean(userId);

        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setId(orders.getId());
        return orderSubmitVO;
    }

    /**
     * 校验用户收货地址
     */
    private void checkDistance(AddressBook addressBook) {
        String userAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        Map<String, String> params = new HashMap<>();
        params.put("address", userAddress);
        params.put("output", "json");
        params.put("ak", baiDuMapProperties.getAk());
        params.put("callback", "showLocation");
        Map<String, Double> userGeoMap = parseGeo(params);

        params.put("address", baiDuMapProperties.getAddress());
        Map<String, Double> shopGeoMap = parseGeo(params);

        double distance = GeoDistinctUtil.calculateDistance(userGeoMap, shopGeoMap);
        log.info("商家距离用户收货地址：{}千米", distance);
        if (distance > 5) {
            throw new OrderBusinessException(MessageConstant.DISTANCE_TOLONG_ERROR);
        }
    }

    /**
     * 解析地理编码返回的结果，获取经纬度
     */
    private static Map<String, Double> parseGeo(Map<String, String> params) {
        String json = HttpClientUtil.doGet(BaiDuMapProperties.GEOCODING_URL, params);
        int start = json.indexOf("(");
        int end = json.lastIndexOf(")");
        json = json.substring(start + 1, end);
        log.info("百度地图返回的地理坐标：{}", json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        int status = jsonObject.getIntValue("status");
        if (status != 0) {
            throw new OrderBusinessException(MessageConstant.BAI_DUMAP_ERROR);
        }
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        Double lng = location.getDouble("lng");
        Double lat = location.getDouble("lat");
        Map<String, Double> map = new HashMap<>();
        map.put("lng", lng);
        map.put("lat", lat);
        return map;
    }

    /**
     * 订单支付
     *
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        ////调用微信支付接口，生成预支付交易单
        //JSONObject jsonObject = weChatPayUtil.pay(
        //        ordersPaymentDTO.getOrderNumber(), //商户订单号
        //        new BigDecimal(0.01), //支付金额，单位 元
        //        "苍穹外卖订单", //商品描述
        //        user.getOpenid() //微信用户的openid
        //);
        //
        //if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //    throw new OrderBusinessException("该订单已支付");
        //}

        // TODO 直接支付成功
        paySuccess(ordersPaymentDTO.getOrderNumber());
        JSONObject jsonObject=new JSONObject();

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 推送语音消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 1);
        jsonObject.put("orderId", ordersDB.getId());
        jsonObject.put("content", "订单号：" + outTradeNo);
        webSocketServer.sendToAllClient(jsonObject.toJSONString());
    }

    /**
     * 历史订单分页查询
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        dto.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> page = orderMapper.historyOrders(dto);
        List<OrderVO> ordersList = page.getResult();
        for (OrderVO orderVO : ordersList) {
            List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetails);
        }
        return new PageResult(page.getTotal(), ordersList);
    }

    /**
     * 查询订单详情
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     */
    @Override
    public void cancel(OrdersCancelDTO dto) {
        Orders orders = orderMapper.getById(dto.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(dto.getCancelReason());
        orderMapper.update(orders);

        // TODO 如果支付应该退款
    }

    /**
     * 再来一单
     */
    @Override
    public void oneMoreOrder(Long id) {
        // 查询明细数据
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
        if (orderDetails.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, cart);
            cart.setCreateTime(LocalDateTime.now());
            cart.setUserId(BaseContext.getCurrentId());
            shoppingCarts.add(cart);
        }

        // 加入购物车
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    /**
     * 订单搜索
     */
    @Override
    public PageResult queryOrder(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Orders> page = orderMapper.queryOrder(dto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO orderStatusCount() {
        Map<Integer, Integer> resultMap = queryStatusCount();
        OrderStatisticsVO vo = new OrderStatisticsVO();
        vo.setDeliveryInProgress(resultMap.get(Orders.DELIVERY_IN_PROGRESS));
        vo.setConfirmed(resultMap.get(Orders.CONFIRMED));
        vo.setToBeConfirmed(resultMap.get(Orders.TO_BE_CONFIRMED));
        return vo;
    }

    /**
     * 统计各个状态的订单数量转成map
     */
    private Map<Integer, Integer> queryStatusCount() {
        List<Map<String, Object>> list = orderMapper.orderStatusCount();
        Map<Integer, Integer> resultMap = new HashMap<>();
        for (Map<String, Object> map : list) {
            Integer status = (Integer) map.get("status");
            Long countLong = (Long) map.get("count");
            resultMap.put(status, countLong.intValue());
        }
        return resultMap;
    }

    /**
     * 接单
     */
    @Override
    public void confirm(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (!Orders.TO_BE_CONFIRMED.equals(orders.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     */
    @Override
    @Transactional
    public void rejectOrder(OrdersRejectionDTO dto) {
        Orders orders = orderMapper.getById(dto.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (!Orders.TO_BE_CONFIRMED.equals(orders.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(dto.getRejectionReason());
        orderMapper.update(orders);

        // TODO 应该退款
    }

    /**
     * 派送订单
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!Orders.CONFIRMED.equals(orders.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!Orders.DELIVERY_IN_PROGRESS.equals(orders.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 客户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 推送语音消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 2);
        jsonObject.put("orderId", orders.getId());
        jsonObject.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(jsonObject.toJSONString());
    }
}
